//
// Created by Administrator on 2022/12/25.
//

#include "FaceTracker.h"
#define ANATIVEWINDOW_RELEASE(window) \
if(window) {                          \
  ANativeWindow_release(window);      \
   window = 0;                        \
}


FaceTracker::FaceTracker(const char *model) {

    Ptr<CascadeDetectorAdapter> mainDetector = makePtr<CascadeDetectorAdapter>(
            makePtr<CascadeClassifier>(model));
    Ptr<CascadeDetectorAdapter> trackingDetector = makePtr<CascadeDetectorAdapter>(
            makePtr<CascadeClassifier>(model));

    DetectionBasedTracker::Parameters DetectorParams;
    tracker = makePtr<DetectionBasedTracker>(mainDetector, trackingDetector, DetectorParams);
    LOGE("FaceTracker构造方法");

    pthread_mutex_init(&mutex,nullptr);
    LOGE("FaceTracker构造方法%d",&mutex);
}

FaceTracker::~FaceTracker() {
    pthread_mutex_destroy(&mutex);
}

void FaceTracker::setANativeWindow(ANativeWindow *window) {

    pthread_mutex_lock(&mutex);
    ANATIVEWINDOW_RELEASE(this->window);
    this->window = window;
    pthread_mutex_unlock(&mutex);
}

void FaceTracker::draw(const Mat& img) {

    pthread_mutex_lock(&mutex);

    do {
        if (!window) {
            break;
        }

        // 宽高 旋转了
        ANativeWindow_setBuffersGeometry(this->window,img.cols,img.rows,WINDOW_FORMAT_RGBA_8888);
        ANativeWindow_Buffer buffer;
        if (ANativeWindow_lock(this->window, &buffer,0)){
            ANATIVEWINDOW_RELEASE(this->window);
            break;
        }
        auto *dstData = static_cast<uint8_t *>(buffer.bits);
        int dislineSize = buffer.stride * 4;
        uint8_t  *srcData = img.data;
        int srcLineSize=  img.cols *4;
        // 一行 一行拷入到buffer
        for (int i = 0; i < buffer.height; ++i) {
            memcpy(dstData+ i *dislineSize,srcData + i* srcLineSize,srcLineSize);
        }
        // 提交数据
        ANativeWindow_unlockAndPost(this->window);
    } while (false);

    pthread_mutex_unlock(&mutex);
}
